package com.liuzy.test;

import com.liuzy.util.FileUtil;
import lombok.Data;

import java.io.File;
import java.io.RandomAccessFile;

@Data
public class Block {
    private File src;
    private int block;
    private long offset;
    private long length;
    private String md5;
    private File blockFile;

    public Block(File file) {
        src = file;
    }

    public String toName() {
        return BlockUtil.leftPad(block) + "_" + getMd5();
    }

    public String getMd5() {
        if (md5 == null) {
            md5 = FileUtil.getMD5(src, offset, length);
        }
        return md5;
    }

    public byte[] getBlockBytes() {
        try (RandomAccessFile raf = new RandomAccessFile(src, "rw")) {
            raf.seek(offset);
            byte[] buff = new byte[(int) length];
            raf.read(buff);
            return buff;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String toString() {
        return toName() + "[" + offset + ", " + length + ']';
    }
}
